<?php
namespace app\controller;

use app\model\Config;
use app\model\Goods;
use app\model\Info;
use app\model\Nav;
use app\model\OrderRecord;
use app\model\User;
use app\model\Web;
use think\facade\Db;
use think\facade\View;

class Index extends Base
{
    public $web;
    public function init(){
        session_start();
        $m = file_exists('./install.log');
        if ($m){
            $web = $_SERVER['SERVER_NAME'];
            if ($_SERVER['SERVER_PORT'] != '80') $web .= ':'.$_SERVER['SERVER_PORT'];
            $web = Web::where('web',$web)->find();
            $nav = Nav::where('pid',0)->where('isshow',1)->with(['son'])->select();
            $this->lang = $web->lang;
            $this->web = $web;
            View::assign('web',$web);
            View::assign('nav',$nav);
            if (!empty($_SESSION['token']))
                View::assign('token',$_SESSION['token']);
        }
    }

    public function install(){
        $m = file_exists('./install.log');
        if ($m) return $this->fail('你已经安装过了,删除install.log再试试');
        $post = input('post.');
        $field = ['db_host', 'db_name', 'db_user', 'db_pass','admin_user', 'admin_pass'];
        foreach ($field AS $key => $value){
            if (empty($post[$value]))
                return $this->fail('必填数据未填写');
        }
        $string = file_get_contents('./database.log');
        $string = str_replace(
            ['{hostname}', '{dataname}', '{username}', '{password}', '{jiekou}'],
            [$post['db_host'], $post['db_name'], $post['db_user'], $post['db_pass'], $post['db_duankou']],
            $string);
        file_put_contents(config_path().'/database.php',$string);
        $m = file_exists('./key.log');
        if (!$m) {
            $uniqid = md5(uniqid() . rand(100, 999) . time());
            file_put_contents('./key.log', $uniqid);
        }else{
            $uniqid = file_get_contents('./key.log');
            if (strlen($uniqid) != 32){
                $uniqid = md5(uniqid() . rand(100, 999) . time());
                file_put_contents('./key.log', $uniqid);
            }
        }
        return $this->msg();
    }

    public function admin(){
        $log = '';
        $sqlFile = './install.sql';
        $sqlContent = file_get_contents($sqlFile);
        // 拆分 SQL 语句（按分号分割）
        $sqlStatements = explode(';', $sqlContent);
        foreach ($sqlStatements as $sql) {
            $sql = trim($sql);
            if (!empty($sql)) {
                try {
                    Db::execute($sql);
                    $log .= "执行成功: $sql\n";
                } catch (\Exception $e) {
                    $log .= "执行失败: " . $e->getMessage()."\n";
                }
            }
        }
        $log .= "数据库初始化完成！";
        $post = input('post.');
        $field = ['admin_user','admin_pass','web','name'];
        foreach ($field AS $key => $value){
            if (empty($post[$value]))
                return $this->fail('必填数据未填写');
        }
        $uniqid = file_get_contents('key.log');
        \app\model\Admin::where('uniqid',$uniqid)->delete();
        $info = \app\model\Admin::create([
            'username' => $post['admin_user'],
            'password' => $post['admin_pass'],
            'rule_id' => 1,
            'uniqid' => $uniqid
        ]);
        if (empty($info->id))
            return $this->fail('安装失败');
        $data = [
            'uniqid' => $uniqid,
            'web' => $post['web'],
            'name' => $post['name'],
            'mobile' => $post['mobile'],
            'status' => 1,
            'lang' => 'cn'
        ];
        Web::where('uniqid',$uniqid)->delete();
        Web::create($data);
        $data = [
            [
                'uniqid' => $uniqid,
                'name' => '首页',
                'url' => 'index',
                'list_template' => '',
                'info_template' => 'index',
                'pid' => 0,
                'lang' => 'cn'
            ], [
                'uniqid' => $uniqid,
                'name' => '关于我们',
                'url' => 'about',
                'list_template' => '',
                'info_template' => 'about',
                'pid' => 0,
                'lang' => 'cn'
            ],[
                'uniqid' => $uniqid,
                'name' => '产品中心',
                'url' => 'goods',
                'list_template' => 'goodslist',
                'info_template' => 'goodsinfo',
                'pid' => 0,
                'lang' => 'cn'
            ],[
                'uniqid' => $uniqid,
                'name' => '新闻资讯',
                'url' => 'news',
                'list_template' => 'newslist',
                'info_template' => 'newsinfo',
                'pid' => 0,
                'lang' => 'cn'
            ],[
                'uniqid' => $uniqid,
                'name' => '联系我们',
                'url' => 'message',
                'list_template' => '',
                'info_template' => 'message',
                'pid' => 0,
                'lang' => 'cn'
            ],
        ];
        Nav::where('uniqid',$uniqid)->delete();
        foreach ($data AS $key => $value) Nav::create($value);
        file_put_contents('./install.log',$log);
        return $this->msg();
    }


    public function index($id = 0){
        $m = file_exists('./install.log');
        if (!$m) {
            header("Location: /install.html");
            die;
        }
        $url = $_SERVER['REQUEST_URI'];
        $path = parse_url($url, PHP_URL_PATH); // 获取路径部分：/about.html
        $filename = basename($path); // 获取文件名：about.html
        $url = str_replace('.html', '', $filename); // 去掉 .html
        $nav = Nav::where('pid',0)
            ->where('lang',$this->web->lang)
            ->where('isshow',1)
            ->with(['son'])
            ->select();
        if(empty($url))$url = 'index';
        $find = Nav::where('url',$url)->with(['content'])->find();
        $info = Info::with(['content'])->find($id);
        $config = Config::gl();
        $all[] = $find->id;
        $son = Nav::where('pid',$find->id)->select()->toArray();
        $ids = array_column($son,'id');
        $all = array_merge($all,$ids);
        while (count($son) > 0){
            $son = Nav::where('pid','IN',$ids)->select()->toArray();
            $ids = array_column($son,'id');
            $all = array_merge($all,$ids);
        }
        if ($url == 'index') $goods = Goods::Paginate(['page' => $this->page,'list_rows' => $this->size]);
        else $goods = Goods::where('nav_id','IN',$all)->paginate(['page' => $this->page,'list_rows' => $this->size]);
        $template = $find->info_template;
        if (empty($id) && $find->web_type == 2)
            $template = $find->list_template;
        if (empty($template))
            return json(['error' => '错误'],500);
        if (!empty($find->content))
            $content = $find->content->content;
        return $this->view('/index/'.$find->lang.'/'.$template,[
            'nav' => $nav,
            'find' => $find,
            'images' => empty($find->images) ? [] : $find->images,
            'config' => $config,
            'info' => $info ?? [],
            'goods' => $goods,
            'content' => $content ?? ''
        ]);
    }

    public function goods($id){
        $info = Goods::with(['attr','attrkey.value_list'])->find($id);
        $nav = Nav::find($info->nav_id);
        $template = $nav->info_template;
        if (empty($template))
            return json(['error' => '错误'],500);
        return $this->view('/index/'.$this->lang.'/'.$template,[
            'goods' => $info ?? [],
            'content' => $info->content ?? ''
        ]);
    }

    public function info($id=0){
        $info = Info::find($id);
        $nav = Nav::find($info->nav_id);
        $template = $nav->info_template;
        if (empty($template))
            return json(['error' => '错误'],500);
        return $this->view('/index/'.$this->lang.'/'.$template,[
            'info' => $info ?? [],
            'content' => $info->content ?? ''
        ]);
    }

    public function cache(){
        $token = input('token');
        $type = input('type',0);
        if ($type == 1){
            $post = input('post.');
            cache($token,$post);
        }
        $res = cache($token);
        return $this->msg($res);
    }

    public function login(){
        if (!empty($_SESSION['user_id'])){
            header("Location: /user.html");
            die;
        }
        $post = input('post.');
        if (!empty($post)){
            $user = User::where('username',$post['username'])->find();
            if (empty($user->id))
                return $this->error('The account does not exist');
            if ($post['password'] != $user->password)
                return $this->error('Password error');
            $token = md5(uniqid().rand(100,999));
            $_SESSION['user_id'] = $user->id;
            $_SESSION['token'] = $token;
            cache($token,$user);
            header("Location: /user.html");
            die;
        }
        return $this->view('/index/'.$this->lang.'/login');
    }

    public function user(){
        $user_id = $this->is_login();
        $user = User::find($user_id);
        $order = OrderRecord::where('user_id',$user_id)->select();
        return $this->view('/index/'.$this->web->lang.'/userinfo',[
            'user' => $user,
            'token' => $_SESSION['token'],
            'order' => $order
        ]);
    }

    protected function is_login(){
        if (empty($_SESSION['user_id'])){
            header("Location: /login.html");
            die;
        }
        return $_SESSION['user_id'];
    }

    protected function error($error){
        return $this->view('/index/error',['error' => 'Password error']);
    }
}
